package drone.iqgc.example ;

import java.util.concurrent.CountDownLatch ;
import java.util.concurrent.TimeUnit ;

import org.slf4j.Logger ;
import org.slf4j.LoggerFactory ;

import io.mavsdk.System ;
import io.mavsdk.action.Action ;
import io.reactivex.Completable ;
import io.reactivex.Observable ;
import io.reactivex.Scheduler ;
import io.reactivex.disposables.Disposable ;
import io.reactivex.schedulers.Schedulers ;

public class TakeoffAndLand
{

	private static final Logger logger = LoggerFactory.getLogger ( TakeoffAndLand.class ) ;

	public static void main (
			String [ ] args
	)
	{
		logger.debug ( "Starting example: takeoff and land..." ) ;

		CountDownLatch latch = new CountDownLatch ( 1 ) ;

		System drone = new System ( "60.205.58.145" , 50042 ) ;

		drone.getAction ( ).arm ( )
		.doOnComplete ( ( ) -> logger.debug ( "Arming..." ) )
		.doOnError ( throwable -> logger.error ( "Failed to arm: " + ( ( Action.ActionException ) throwable ).getCode ( ) ) )
		.andThen ( 
				drone.getAction ( ).takeoff ( )
				.doOnComplete ( ( ) -> logger.debug ( "Taking off..." ) )
				.doOnError ( throwable -> logger.error ( "Failed to take off: " + ( ( Action.ActionException ) throwable ).getCode ( ) ) ) 
			)
		.delay ( 50 , TimeUnit.SECONDS )
		.andThen ( 
				drone.getAction ( ).land ( )
				.doOnComplete ( ( ) -> logger.debug ( "Landing..." ) )
				.doOnError ( throwable -> logger.error ( "Failed to land: " + ( ( Action.ActionException ) throwable ).getCode ( ) ) ) 
			)
		.subscribe ( latch::countDown , throwable -> latch.countDown ( ) ) ;

		try
		{
			latch.await ( ) ;
		} catch ( InterruptedException ignored )
		{
			// This is expected
		}
		//
	}
}
